package priv.yiyuan.example.design.proxy;

/**
 * 文件访问代理
 *
 * @author YiYuan
 * @data 2025/9/25
 * @apoNote
 */
public class FileAccessProxy implements FileOperation {

    /**
     * 持有实际操作文件类的引用
     */
    private RealFileOperation realFileOperation;

    private String currentUser;

    public FileAccessProxy(String currentUser) {
        this.realFileOperation = new RealFileOperation();
        this.currentUser = currentUser;
    }

    private boolean checkPermission(String filePath, String operationType) {

        if (filePath.contains("sensitive") && "write".equals(operationType) && !"admin".equals(currentUser)) {
            System.out.println("[文件访问代理] 权限不足: 用户 " + currentUser + " 无权写入敏感文件: " + filePath);
            return false;
        }

        System.out.println("[文件访问代理] 权限检查通过: 用户 " + currentUser + " 可以执行 " + operationType + " 操作。");
        return true;
    }

    @Override
    public void write(String filePath, String content) {
        if (this.checkPermission(filePath, "write")) {
            realFileOperation.write(filePath, content);
        }
    }

    @Override
    public String read(String filePath) {
        if (this.checkPermission(filePath, "read")) {
            return realFileOperation.read(filePath);
        }

        return "";
    }
}
